//
//  SearchVC.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/2/3.
//  Copyright © 2021 shengYang. All rights reserved.
//

#import "SearchVC.h"
#import "searchHistoryCell.h"
#import "BaseCollectionCell.h"
#import "pickCelll.h"
#import "signUpCollectionCell.h"
#import "SignUPInforVC.h"

@interface SearchVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIView *back_view;
@property (strong, nonatomic) IBOutlet UILabel *type_lab;
@property (strong, nonatomic) IBOutlet UIButton *type_btn;
@property (strong, nonatomic) IBOutlet UILabel *status_lab;
@property (strong, nonatomic) IBOutlet UIButton *status_btn;
@property (strong, nonatomic) IBOutlet UITextField *search_field;
@property (strong, nonatomic) IBOutlet UICollectionView *left_collectionView;
@property (strong, nonatomic) IBOutlet UICollectionView *right_collection_view;
@property (strong, nonatomic) IBOutlet UIView *line_view;
@property (strong, nonatomic) IBOutlet UIView *top_view;
@property (strong, nonatomic) IBOutlet UIButton *search_btn;

@property (strong, nonatomic) IBOutlet UIImageView *back_img;
@end

@implementation SearchVC{
    BOOL search ;//yes 已搜索、 no 没有搜索（初进页面）
    NSMutableArray *listLeft;//左边内容数组
    NSMutableArray *listRight;//右边内容数组
    NSMutableArray *resultArr;//搜索结果数组
    
    UITableView *pickLeft;//类型选择
    UITableView *pickRight;//状态选择
    NSArray *pickLeftArr;//类型数组
    NSArray *pickRightArr;//状态数组
    
    NSMutableDictionary *paramDic;//参数字典
    UICollectionView *collection_view;
    NSMutableArray *hotNameArr;//热词数组
    
    NSInteger page_index;//页码
    RequestServices *service;
    NSMutableDictionary *typeDic;
    NSMutableDictionary *statusDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索";
    [self.backKuang setHidden:YES];
    hotNameArr = [NSMutableArray array];

    NSAttributedString *attrString1 = [[NSAttributedString alloc] initWithString:@"   请输入关键字搜索" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:self.search_field.font}];
    self.search_field.attributedPlaceholder = attrString1;
    APPViewBorderRadius(self.search_field, 10, 1, Base_lineColor);
    APPViewBorderRadius(self.type_btn, 5, .5, Base_lineColor);
    APPViewBorderRadius(self.status_btn, 5, .5, Base_lineColor);
    self.search_field.delegate = self;
    self.search_field.tag = 6666;
    self.type_btn.titleLabel.font = self.type_lab.font =self.status_btn.titleLabel.font = self.status_lab.font = self.search_btn.titleLabel.font = self.search_field.font = AutoLabFont2;
   //点击搜索
    [self.search_btn addTarget:self action:@selector(searchHotWord) forControlEvents:UIControlEventTouchUpInside];
    paramDic = [NSMutableDictionary dictionary];
    [self.back_view insertSubview:self.back_img atIndex:0];
    [self showCollectionView];
    [self addPickview];
    
    
    resultArr = [NSMutableArray array];
    typeDic = [NSMutableDictionary dictionary];
    [typeDic setValue:@"-1" forKey:@"type"];//默认全部
    statusDic = [NSMutableDictionary dictionary];
    [statusDic setValue:@"-1" forKey:@"status"];//默认全部
    page_index = 1;
    [self loadRequest];
}

//添加视图
-(void)showCollectionView{
    search = NO;
    self.left_collectionView.delegate = self.right_collection_view.delegate = self;
    self.left_collectionView.dataSource = self.right_collection_view.dataSource = self;
    
    [self.left_collectionView registerNib:[UINib nibWithNibName:@"searchHistoryCell" bundle:nil] forCellWithReuseIdentifier:@"searchHistoryCell"];
    [self.left_collectionView registerNib:[UINib nibWithNibName:@"BaseCollectionCell" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BaseCollectionCell"];
    
    [self.right_collection_view registerNib:[UINib nibWithNibName:@"searchHistoryCell" bundle:nil] forCellWithReuseIdentifier:@"searchHistoryCell"];
    [self.right_collection_view registerNib:[UINib nibWithNibName:@"BaseCollectionCell" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BaseCollectionCell"];
    listLeft = [NSMutableArray array];
}

//本地存储
-(void)showDefaultArr{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults objectForKey:@"searchHot"]) {
        listRight = [NSMutableArray arrayWithArray:[userDefaults objectForKey:@"searchHot"]];
    }else{
        listRight = [NSMutableArray array];
    }
}

-(void)addPickview{
    
    pickLeftArr = [NSArray arrayWithObjects:@"全部",@"比赛",@"活动",nil];
    [self.type_btn addTarget:self action:@selector(showLeftPick) forControlEvents:UIControlEventTouchUpInside];
    
    
    pickRightArr = [NSArray arrayWithObjects:@"全部",@"未开始",@"报名中",@"评奖中",@"已结束",nil];
    [self.status_btn addTarget:self action:@selector(showRightPick) forControlEvents:UIControlEventTouchUpInside];
}

//左边选择框
-(void)showLeftPick{
    
    pickLeft = [[UITableView alloc]init];
    pickLeft.tag = 1001;
    pickLeft.delegate = self;
    pickLeft.dataSource = self;
    pickLeft.backgroundColor = [UIColor clearColor];
    [self.view addSubview:pickLeft];
    [pickLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.type_btn.mas_top);
        make.left.equalTo(self.type_btn);
        make.width.equalTo(self.type_btn);
        make.height.mas_equalTo(self.type_btn.frame.size.height * pickLeftArr.count);
   }];
    
    [pickLeft registerNib:[UINib nibWithNibName:@"pickCelll" bundle:nil] forCellReuseIdentifier:@"pickCelll"];
     pickLeft.separatorColor = [UIColor clearColor];
}

//右边选择框
-(void)showRightPick{
    
    pickRight = [[UITableView alloc]init];
    pickRight.tag = 1002;
    pickRight.delegate = self;
    pickRight.dataSource = self;
    pickRight.backgroundColor = [UIColor clearColor];
    [self.view addSubview:pickRight];
    [pickRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.status_btn.mas_top);
        make.left.equalTo(self.status_btn);
        make.width.equalTo(self.status_btn);
        make.height.mas_equalTo(self.status_btn.frame.size.height * pickRightArr.count);
   }];
    
    [pickRight registerNib:[UINib nibWithNibName:@"pickCelll" bundle:nil] forCellReuseIdentifier:@"pickCelll"];
     pickRight.separatorColor = [UIColor clearColor];
}

-(void)loadRequest{
    service = [[RequestServices alloc]initWithDelegate:self];
    service.view = self.view;
    [service requestSearchWord:3 tag:8000];//3 阿列夫赛道搜索
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self searchHotWord];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text == nil) {
        //如果为空
        [statusDic setValue:@"" forKey:@"hotName"];
    }else{
        [statusDic setValue:textField.text forKey:@"hotName"];
    }
}

//点击搜索按钮
-(void)searchHotWord{
    UITextField *textField = [self.view viewWithTag:6666];
    [textField resignFirstResponder];
    //输入不一样再添加
    if (![textField.text isEqualToString:statusDic[@"hotName"]]) {
        [statusDic setValue:textField.text forKey:@"hotName"];
    }
    if ([statusDic[@"hotName"] CheckNSStringData]) {
        [service requestAliefuGymList:page_index size:10 status:[statusDic[@"status"] integerValue] type:[typeDic[@"type"] integerValue] keyword:statusDic[@"hotName"] tag:8010];
    }else{
        [SVProgressHUD showErrorWithStatus:@"请输入关键字搜索"];
    }
}


#pragma mark ---------------- requestDelegate
-(void)getFinished:(NSDictionary *)obj tag:(long long)tag{
    [self HideLoading];
    if (tag == 8000) {
        //获取热词
        listLeft = [SearchWordModel mj_objectArrayWithKeyValuesArray:obj[@"list"]];
        //热词数组
        if (listLeft.count > 0) {
            for (int i = 0; i<listLeft.count; i++) {
                SearchWordModel *model = listLeft[i];
                [hotNameArr addObject:model.hotName];
            }
        }
        [self.left_collectionView reloadData];
        [self showDefaultArr];
        [self.right_collection_view reloadData];
    }
    
    if (tag == 8010) {
        //点击热词
        search = YES;
        if ([statusDic[@"hotName"] CheckNSStringData]) {
            [listRight addObject:statusDic[@"hotName"]];
            if (listRight.count > 3) {
                [listRight removeObjectsInRange:NSMakeRange(3, listRight.count - 3)];
            }
        }
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:listRight forKey:@"searchHot"];
        [userDefaults synchronize];
        [self.left_collectionView setHidden:YES];
        [self.right_collection_view setHidden:YES];
        [self.line_view setHidden:YES];
        [self addCollectionView];
        resultArr = [AliefuModel mj_objectArrayWithKeyValuesArray:obj[@"list"]];
        [collection_view reloadData];
    }
    
    if (tag == 8020) {
        NSMutableArray *tempArr = [NSMutableArray arrayWithArray:obj[@"list"]];
        [resultArr addObjectsFromArray:[AliefuModel mj_objectArrayWithKeyValuesArray:tempArr]];
        [collection_view reloadData];
    }
}

-(void)getError:(NSError *)error tag:(long long)tag{
    [self HideLoading];
    [self ShowNewMsg:error.domain];
}


#pragma mark -------------------------- tableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 1001) {
        return pickLeftArr.count;
    }else{
        return pickRightArr.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{   
    return self.status_btn.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    pickCelll *cell = [tableView dequeueReusableCellWithIdentifier:@"pickCelll" forIndexPath:indexPath];
    if (tableView.tag == 1001) {
        cell.pick_lab.text = [NSString stringWithFormat:@"%@",pickLeftArr[indexPath.row]];
    }
    if (tableView.tag == 1002){
        cell.pick_lab.text = [NSString stringWithFormat:@"%@",pickRightArr[indexPath.row]];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    search = YES;
    [self.view endEditing:YES];
    if (tableView.tag == 1001) {
        [pickLeft removeFromSuperview];
        [self.type_btn setTitle:[NSString stringWithFormat:@"%@",pickLeftArr[indexPath.row]] forState:UIControlStateNormal];
        if ([pickLeftArr[indexPath.row] isEqualToString: @"全部"]) {
            [typeDic setValue:@"-1" forKey:@"type"];
        }else if ([pickLeftArr[indexPath.row] isEqualToString: @"比赛"]){
            [typeDic setValue:@"1" forKey:@"type"];
        }else if ([pickLeftArr[indexPath.row] isEqualToString: @"活动"]){
            [typeDic setValue:@"0" forKey:@"type"];
        }
    }
    
    if (tableView.tag == 1002) {
        [pickRight removeFromSuperview];
        [self.status_btn setTitle:[NSString stringWithFormat:@"%@",pickRightArr[indexPath.row]] forState:UIControlStateNormal];
        if ([pickRightArr[indexPath.row] isEqualToString: @"全部"]) {
            [statusDic setValue:@"-1" forKey:@"status"];
        }else if ([pickRightArr[indexPath.row] isEqualToString: @"未开始"]){
            [statusDic setValue:@"0" forKey:@"status"];
        }else if ([pickRightArr[indexPath.row] isEqualToString: @"报名中"]){
            [statusDic setValue:@"1" forKey:@"status"];
        }else if ([pickRightArr[indexPath.row] isEqualToString: @"评奖中"]){
            [statusDic setValue:@"2" forKey:@"status"];
        }else if ([pickRightArr[indexPath.row] isEqualToString: @"已结束"]){
            [statusDic setValue:@"3" forKey:@"status"];
        }
    }
    [statusDic removeObjectForKey:@"hotName"];
    [self.left_collectionView setHidden:YES];
    [self.right_collection_view setHidden:YES];
    [self.line_view setHidden:YES];
    [self addCollectionView];
    [self headerRefresh:[statusDic[@"status"] integerValue] type:[typeDic[@"type"] integerValue]];
}

#pragma mark ----------------------CollectionView
-(void)addCollectionView{
    if (collection_view.subviews.count > 0) {
        [collection_view removeAllSubivews];        
    }
    //边框隐藏
    [self.back_img setHidden:YES];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 20;

    collection_view = [[UICollectionView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.top_view.frame),CGRectGetMaxY((self.top_view.frame)),  SCREEN_W*0.925, self.back_view.frame.size.height*0.8) collectionViewLayout:flowLayout];
    collection_view.backgroundColor = [UIColor clearColor];
    collection_view.tag = 5555;
    collection_view.showsHorizontalScrollIndicator = NO;
    [self.back_view addSubview:collection_view];
    [collection_view registerNib:[UINib nibWithNibName:@"signUpCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"signUpCollectionCell"];
    collection_view.delegate = self;
    collection_view.dataSource = self;
    
    //左划
    collection_view.mj_trailer =[MJRefreshTrailer trailerWithRefreshingBlock:^{
        [self footerRefresh:[self->statusDic[@"status"] integerValue] type:[self->typeDic[@"type"] integerValue]];
    }];
    collection_view.mj_trailer.hidden = YES;
}

- (void)headerRefresh:(NSInteger)status type:(NSInteger)type
{
    [resultArr removeAllObjects];
    [service requestAliefuGymList:page_index size:10 status:status type:type keyword:statusDic[@"hotName"] tag:8010];
}

- (void)footerRefresh:(NSInteger)status type:(NSInteger)type
{
    page_index++;
    [service requestAliefuGymList:page_index size:10 status:status type:type keyword:statusDic[@"hotName"] tag:8020];
}


#pragma mark ----- collectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.left_collectionView) {
        return listLeft.count;
    }
    if (collectionView == self.right_collection_view) {

        return listRight.count;
    }
    return resultArr.count;
}

//每个item的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == self.left_collectionView) {
        CGFloat width = [[NSString stringWithFormat:@"%@",hotNameArr[indexPath.item]] boundingRectWithSize:CGSizeMake(0, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : AutoLabFont2} context:nil].size.width;
        return CGSizeMake(width+20, 50);
    }
    else if (collectionView == self.right_collection_view) {
        CGFloat width = [[NSString stringWithFormat:@"%@",listRight[indexPath.item]] boundingRectWithSize:CGSizeMake(0, 40) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : AutoLabFont2} context:nil].size.width;
        return CGSizeMake(width+60, 50);
    }else{
        return CGSizeMake(collectionView.frame.size.width/3,collectionView.frame.size.height * 0.9);
    }
}

//每个section的header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    BaseCollectionCell *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BaseCollectionCell" forIndexPath:indexPath];
    view.base_lab.font = AutoLabFont2;
    view.base_lab.textColor = [UIColor whiteColor];
    if (collectionView == self.left_collectionView) {
         view.base_lab.text = @"     热门搜索";
    }
    if (collectionView == self.right_collection_view) {
        view.base_lab.text = @"      历史搜索";
    }
    return view;
}

//header的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (!search) {
        return CGSizeMake(collectionView.frame.size.width/2, collectionView.frame.size.height*0.2);
    }else{
        return CGSizeMake(0,0); 
    }
}

//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (!search) {//无搜索即为初进页面
        searchHistoryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchHistoryCell" forIndexPath:indexPath];
        if (collectionView == self.left_collectionView) {
            cell.model = listLeft[indexPath.item];
            [cell.delete_btn setHidden:YES];
        }
        if (collectionView == self.right_collection_view) {
            cell.label.text = [NSString stringWithFormat:@"  %@",listRight[indexPath.item]];
            [cell.delete_btn setHidden:NO];
            cell.delete_btn.tag = 2222+indexPath.item;
            [cell.delete_btn addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }else{
        signUpCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"signUpCollectionCell" forIndexPath:indexPath];
        cell.model = resultArr[indexPath.item];
       //点击进入
        cell.join_btn.tag = indexPath.item + 1000;
        [cell.join_btn addTarget:self action:@selector(comeToInfor:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.left_collectionView) {
        //点击热词 获取列表页
        SearchWordModel *model = listLeft[indexPath.row];
        [statusDic setValue:model.hotName forKey:@"hotName"];
        [service requestAliefuGymList:page_index size:10 status:[statusDic[@"status"] integerValue] type:[typeDic[@"type"] integerValue] keyword:statusDic[@"hotName"] tag:8010];
    }
}

//四周边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (collectionView == self.left_collectionView || collectionView == self.right_collection_view) {
        return UIEdgeInsetsMake(20, 20, 10, 10);
    }
    return UIEdgeInsetsMake(20, 20, 20, 20);
}

//删除历史搜索
-(void)delete:(UIButton *)sender{
    [listRight removeObjectAtIndex:sender.tag-2222];
    [self.right_collection_view reloadData];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:listRight forKey:@"searchHot"];
    
}

//查看详情
-(void)comeToInfor:(UIButton *)sender{
    NSInteger tag = sender.tag - 1000;
    SignUPInforVC *vc = [[SignUPInforVC alloc]init];
    [self PushToViewController:vc];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
